#include "listener.h"

#include "eventhandler.h"

static EventHandler* EventHandlerInstance = nullptr;

EventHandler::EventHandler() {
	m_CurrentEventVectorID = 1;
}

EventHandler* EventHandler::GetInstance() {
	if(EventHandlerInstance == nullptr) {
		EventHandlerInstance = new EventHandler();
	}

	return EventHandlerInstance;
}

void EventHandler::SendEvent(EventMessage* e) {

	if(m_CurrentEventVectorID == 1) {
		m_EventVector1.push_back(e);
	} else if(m_CurrentEventVectorID == 2) {
		m_EventVector2.push_back(e);
	}
}

void EventHandler::Update() {
	int i, n;
	EventMessage* message;

	if(m_CurrentEventVectorID == 1) {
		n = m_EventVector1.size();

		for(i = 0; i < n; i++) {
			message = m_EventVector1.back();
			Listener* listener = message->m_Destination;
			listener->OnEvent(message->m_Event);
			m_EventVector1.pop_back();
		}

		m_EventVector1.clear();
		m_CurrentEventVectorID = 2;

	} else if(m_CurrentEventVectorID == 2) {
		n = m_EventVector2.size();

		for(i = 0; i < n; i++) {
			message = m_EventVector2.back();
			Listener* listener = message->m_Destination;
			listener->OnEvent(message->m_Event);
			m_EventVector2.pop_back();
		}

		m_EventVector2.clear();
		m_CurrentEventVectorID = 1;

	}
}